package com.alan.libapi.api;

import com.alan.library.allog.KLog;

import java.io.IOException;

/**
 * @className: ALTcpClient
 * @describtion: ALTcpClient
 * @author: AlanWang
 * @email: 850267876@qq.com
 * @time: 2016/4/28 14:56
 */
public class ALTcpClient implements IALTcpClient {

    private String hostIp;
    private int port;
    private ALTcpSocketHelper alTcpSocketHelper;

    public ALTcpClient(String hostIp, int port) {
        this.hostIp = hostIp;
        this.port = port;
        alTcpSocketHelper = new ALTcpSocketHelper(hostIp, port);
        try {
            alTcpSocketHelper.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过Tcp发送请求
     * @param requestStr
     * @return
     */
    public String request(String requestStr) {
        KLog.d("requestStr = " + requestStr);
        String responseStr = null;
        boolean isSend;
        try {
            isSend = alTcpSocketHelper.sendData(requestStr.getBytes());
            if (isSend) {
                byte[] responseData = alTcpSocketHelper.receiveData();
                if (responseData != null) {
                    responseStr = new String(responseData);
                    KLog.d("responseString = " + responseStr);
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseStr;
    }

    @Override
    public boolean isAlive() {
        return alTcpSocketHelper.isAlive();
    }

    @Override
    public void retryConnection() throws IOException {
        alTcpSocketHelper.connect();
    }

    @Override
    public void close() throws IOException {
        alTcpSocketHelper.closeSocket();
    }
}
